package tts.controller.roles;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.RolesHome;
import tts.dao.UsersHome;
import tts.model.Roles;
import tts.model.Users;

public class Insert extends RedirectAction {

	//fields
	private static final long serialVersionUID = -9037931792240948793L;
	@Autowired
	private RolesHome rolesHome;
	@Autowired
	private UsersHome usersHome;
	private Roles roleIns;
	private ArrayList<String> strings;


	//get & set	
	public Roles getRoleIns() {
		return roleIns;
	}
	public void setRoleIns(Roles roleIns) {
		this.roleIns = roleIns;
	}	
	public ArrayList<String> getStrings() {
		return strings;
	}
	public void setStrings(ArrayList<String> strings) {
		this.strings = strings;
	}

	//methods
	public String insert() {
		try {
			rolesHome.insert(this.roleIns);
			for (String s : strings) {
				Users user = usersHome.findByUsername(s);
				this.roleIns.getUsersList().add(user);
				user.getRolesList().add(this.roleIns);
			}
		} catch (RuntimeException e) {
			if (e.getCause().getCause().getMessage().startsWith("Duplicate"))
				addFieldError("roleIns.roleName", getText("val.duplicate.role"));
			else addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("role.inserted"));
		return SUCCESS;
	}
}